package com.base.cn.platform.os.common.reqToken;

import com.base.cn.platform.os.common.j2cache.CustomCacheChannel;
import com.base.cn.platform.os.common.j2cache.J2CacheRegion;
import com.base.cn.platform.os.common.utils.ObjectUtils;
import com.base.cn.platform.os.common.utils.StringUtils;
import com.base.cn.platform.os.common.utils.web.WebUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 访问Token工具类
 *
 * @author s.li
 * @date 2019/02/16
 */
@Component
@Slf4j
public class ReqTokenTools {
    public static int WEB=1;
    public static int MOBILE = 2;
    public static String webKey = "w_r_t";
    public static String mobileKey = "m_r_t";
    //原来的KEY
    public static String OLD_KEY = "req_old_token_key";

    @Autowired
    private CustomCacheChannel customCacheChannel;

    /**
     * 生成Token
     * @param request HttpServletRequest
     * @param response HttpServletResponse
     * @param type ReqTokenTools.WEB,ReqTokenTools.MOBILE
     */
    public void genToken(HttpServletRequest request,HttpServletResponse response,int type){
        /*String referer = request.getHeader("Referer");
        String oldToken = null;
        if(type==WEB){
            oldToken = WebUtils.getCookie(request,webKey);
        }
        if(type==MOBILE){
            oldToken = WebUtils.getCookie(request,mobileKey);
        }
        if(!StringUtils.isNotEmpty(referer) || !StringUtils.isNotEmpty(oldToken)){
            String token = StringUtils.getRandomString(32);
            ReqToken reqToken = new ReqToken(token,System.currentTimeMillis());
            cacheChannel.set("demo4.0-one_day_region",token,reqToken);
            if(type==WEB){
                WebUtils.setCookie(response,webKey,token,1);
            }
            if(type==MOBILE){
                WebUtils.setCookie(response,mobileKey,token,1);
            }
            if(StringUtils.isNotEmpty(oldToken)){
                cacheChannel.evict("demo4.0-one_day_region",oldToken);
            }
        }*/
        long nowTime = System.currentTimeMillis();
        String oldToken = null;
        if(type==WEB){
            oldToken = WebUtils.getCookie(request,webKey);
        }
        if(type==MOBILE){
            oldToken = WebUtils.getCookie(request,mobileKey);
        }
        String token = StringUtils.getRandomString(32);
        ReqToken reqToken = new ReqToken(token,nowTime);
        customCacheChannel.set(J2CacheRegion.ONE_DAY_REGION.getKey(),token,reqToken);
        if(type==WEB){
            WebUtils.setCookie(response,webKey,token,1);
        }
        if(type==MOBILE){
            WebUtils.setCookie(response,mobileKey,token,1);
        }
        //如果有原token，则进行缓存
        if(StringUtils.isNotEmpty(oldToken)){
            Map<String,ReqToken> tokenMap = (Map<String,ReqToken>)customCacheChannel.get(J2CacheRegion.ONE_DAY_REGION.getKey(),OLD_KEY).getValue();
            if(tokenMap==null){
                tokenMap = new HashMap<>();
            }
            tokenMap.put(oldToken,new ReqToken(oldToken,nowTime));
            Map<String,ReqToken> _tokenMap = new HashMap<>(tokenMap);
            long minute = 1;//超过一分钟的，则进行删除
            tokenMap.forEach((k,v)->{
                long _time = nowTime - v.getTime();
                long s = _time / 1000 / 60;
                if(s >= minute){
                    _tokenMap.remove(k);
                    customCacheChannel.evict(J2CacheRegion.ONE_DAY_REGION.getKey(),k);
                }
            });
            customCacheChannel.set(J2CacheRegion.ONE_DAY_REGION.getKey(),OLD_KEY,_tokenMap);
        }
    }

    /**
     * 验证Token
     * @param token
     * @return true通过，false未通过
     */
    public boolean validateToken(String token){
        ReqToken reqToken = (ReqToken) customCacheChannel.get(J2CacheRegion.ONE_DAY_REGION.getKey(),token).getValue();
        if(!ObjectUtils.isNotEmpty(reqToken) || !token.equals(reqToken.getToken())){
            return false;
        }
        return true;
    }

    /**
     * 清除
     * @param token
     */
    public void cleanReqToken(HttpServletRequest request,HttpServletResponse response,String token,int type){
        if(type==WEB){
            WebUtils.deleteCookie(request,response,webKey);
        }
        if(type==MOBILE){
            WebUtils.deleteCookie(request,response,mobileKey);
        }
        customCacheChannel.evict(J2CacheRegion.ONE_DAY_REGION.getKey(),token);
    }


}
